package com.etop.learnapp.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.etop.learnapp.R;
import com.etop.learnapp.util.BitmapCreate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;

/**
 * Created by John on 2015/10/26 0026.
 */
public class DetailActivity extends AppCompatActivity implements SurfaceHolder.Callback{
    LinkedList<View> list = new LinkedList();
    String[] FileName=null;
    String BFile= null;
    LinearLayout mLinearLayout;
    StringBuilder sb;
    AssetManager am;
    ScrollView sv;
    Activity ac;
    String dirName;
    int index = 0;
    private Toolbar toolbar;
    private ScrollView mScrollView;
    int keySelect;
    int chapterSelect;
    private MediaPlayer mediaPlayer;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private int resID;
    private boolean hasShownMedia = false;
    private boolean hasMedia = false;
    private final TranslateAnimation tAnim = new TranslateAnimation(-900, 0, 0, 0);
    private final RotateAnimation rAnim = new RotateAnimation(-80, 0);
    private final ScaleAnimation sAnim = new ScaleAnimation(0, 1, 0, 1);
    private final AlphaAnimation aAnim = new AlphaAnimation(0.0f, 1.0f);
    private  Animation[] animations =null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        initToolBar();
        initAnim();
        mLinearLayout = (LinearLayout)findViewById(R.id.deLinear);
        mScrollView = (ScrollView) findViewById(R.id.scrollView);
        keySelect = getIntent().getIntExtra("keySelect",-1);
        chapterSelect = getIntent().getIntExtra("chapterSelect",-1);
        if(keySelect==4&&chapterSelect==5)
        {
            hasMedia=true;
        }
        dirName = chapterSelect+"_"+keySelect;
        ac=this;
        am = this.getAssets();
        try {
            FileName = am.list(dirName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(FileName.length>0)
        {
            try {
                init(FileName[0]);
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("io exception");
            }


            Button previous = (Button)findViewById(R.id.privious);
            previous.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (index != 1) {
                        View lastView = list.get(list.size() - 1);
                        list.remove(list.size() - 1);
                        mLinearLayout.removeView(lastView);
                        if(index!=FileName.length)
                        {
                            hasShownMedia = false;
                        }
                        index--;
                    }
                }
            });

            Button next = (Button) findViewById(R.id.next);
            next.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(index<FileName.length){
                        try {
                            init(FileName[index]);
                            mScrollView.postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                    mScrollView.fullScroll(ScrollView.FOCUS_DOWN);
                                }
                            },100);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    else {
                        if(hasShownMedia||!hasMedia)
                        {
                            Snackbar.make(v, "本小节已经完了", Snackbar.LENGTH_LONG)
                                    .setAction("Action", null).show();
                        }
                        else
                        {
                            initSurface();
                            hasShownMedia = true;
                        }
                    }
                }
            });
        }

    }

    private void initAnim() {
        tAnim.setDuration(800);
        rAnim.setDuration(800);
        sAnim.setDuration(800);
        aAnim.setDuration(800);
        animations = new Animation[]{sAnim,rAnim,aAnim,tAnim};
    }

    private void initSurface()
    {
        if(surfaceView==null)
        {
            surfaceView = new SurfaceView(this);
            surfaceHolder = surfaceView.getHolder();
            surfaceHolder.addCallback(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    720);
            lp.setMargins(5, 10, 5, 10);
            surfaceView.setLayoutParams(lp);
        }
        mLinearLayout.addView(surfaceView);
        list.add(surfaceView);
        index++;
        int keySelect =  getIntent().getIntExtra("keySelect", -1);
        String fileName="sp5_"+keySelect;
        resID=getResources().getIdentifier(fileName,"raw",getPackageName());
    }
    class PlayMovie extends Thread {   //播放视频的线程

        int post = 0;

        public PlayMovie(int post) {
            this.post = post;

        }

        @Override
        public void run() {
            Message message = Message.obtain();
            try {
                if(mediaPlayer==null)
                {
                    mediaPlayer = MediaPlayer.create(DetailActivity.this, resID);
                }
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                mediaPlayer.setDisplay(surfaceHolder);
                mediaPlayer.start();
            } catch (Exception e) {
                message.what = 2;
                Log.e("hck", e.toString());
            }
            super.run();
        }
    }
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        new PlayMovie(0).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        System.gc();
    }
    private void initToolBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar_include);
        setSupportActionBar(toolbar);
        setTitle(getIntent().getStringExtra("keyName"));
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
    }
    public boolean isPicture(String File){
        if (File.endsWith(".txt")){
            return false;
        }
        else return true;
    }
    public void init(String File) throws IOException {
        if(isPicture(File)){
            File = "assets://"+ dirName +"/"+File;
            ImageView iv = new ImageView(this);
            iv.setScaleType(ImageView.ScaleType.FIT_START);
            iv.setAdjustViewBounds(true);
            new BitmapCreate(File,this,iv);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.setMargins(5, 10, 5, 10);
            iv.setLayoutParams(lp);
            BFile=File;
            iv.setOnClickListener(new View.OnClickListener() {
                                      String UR = BFile;
                                      @Override
                                      public void onClick(View v) {
                                          Intent intent = new Intent(DetailActivity.this, PicActivity.class);
                                          intent.putExtra("Resources", UR);
                                          startActivity(intent);
                                      }
                                  }
            );
            list.add(iv);
            mLinearLayout.addView(iv);
            iv.startAnimation(animations[index % 4]);


        }
        else {
            TextView tv;
            File = dirName +"/"+File;
            System.out.println(File);
            InputStream is = am.open(File);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            tv = new TextView(this);
            tv.setText(sb);
            tv.setTextSize(18);
            tv.startAnimation(animations[index%4]);
            list.add(tv);
            mLinearLayout.addView(tv);
        }
        index++;
    }

}
